package com.cyt.work.wb.service.impl;

import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.hutool.core.date.DateUtil;
import com.cyt.base.model.dto.ReturnResult;
import com.cyt.base.util.*;
import com.cyt.sys.dao.SysFileDao;
import com.cyt.sys.model.po.SysFile;
import com.cyt.sys.model.po.SysUser;
import com.cyt.sys.service.impl.BaseServiceImpl;
import com.cyt.sys.util.EasyPoiUtil;
import com.cyt.sys.util.FilePathUtil;
import com.cyt.work.association.model.vo.WxAssociationUserVerifyImportVo;
import com.cyt.work.util.cache.ListToMapUtil;
import com.cyt.work.wb.dao.WxWbBulidDao;
import com.cyt.work.wb.dao.WxWbRoomDao;
import com.cyt.work.wb.model.po.WxWbBulid;
import com.cyt.work.wb.model.po.WxWbRoom;
import com.cyt.work.wb.model.vo.WxWbBulidVo;
import com.cyt.work.wb.model.vo.WxWbRoomExportVo;
import com.cyt.work.wb.model.vo.WxWbRoomVo;
import com.cyt.work.wb.service.WxWbBulidService;
import com.cyt.work.wb.service.WxWbRoomService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.iherus.codegen.qrcode.SimpleQrcodeGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.*;

/**
 * 维保模块-房间表Service层实现类
 *
 * @author ding xu
 * @date 2019-11-27 17:42:26
 */
@Service("wxWbRoomService")
public class WxWbRoomServiceImpl extends BaseServiceImpl<WxWbRoom> implements WxWbRoomService {

    @Resource
    private WxWbRoomDao wxWbRoomDao;

    @Resource
    private SysFileDao sysFileDao;

    @Resource
    private WxWbBulidDao wxWbBulidDao;

    @Autowired
    public void setBaseDao(WxWbRoomDao wxWbRoomDao) {
        this.baseDao = wxWbRoomDao;
    }

    /**
     * 查询对象集合
     *
     * @param wxWbRoomVo 对象
     * @return List 对象集合
     * @author ding xu
     * @date 2019-11-27 17:42:26
     */
    @Override
    public List<WxWbRoomVo> listExample(WxWbRoomVo wxWbRoomVo) {
        return wxWbRoomDao.selectByCondition(wxWbRoomVo);
    }

    /**
     * 分页查询
     *
     * @param wxWbRoomVo 接受参数对象
     * @param pageNum          分页数
     * @param pageSize         每页显示条数
     * @return ReturnResult
     * @author ding xu
     * @date 2019-11-27 17:42:26
     */
    @Override
    public ReturnResult page(WxWbRoomVo wxWbRoomVo, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        PageHelper.orderBy(" create_time desc");
        List<WxWbRoomVo> list = listExample(wxWbRoomVo);
        PageInfo<WxWbRoomVo> page = new PageInfo<>(list);
        return new ReturnResult(page.getList(), page.getTotal(), page.isHasNextPage());
    }

    /**
     * 添加或更新
     *
     * @param wxWbRoomVo 参数接受对象
     * @param sysUser      当前用户
     * @return ReturnResult
     * @author ding xu
     * @date 2019-11-27 17:42:26
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult addOrUpdate(HttpServletRequest request,WxWbRoomVo wxWbRoomVo, SysUser sysUser) {
        if (StringUtils.isBlank(wxWbRoomVo.getId())) {
            WxWbRoom wxWbRoom = new WxWbRoom(sysUser);
            wxWbRoom.setApplyId(wxWbRoomVo.getApplyId());
            wxWbRoom.setRoomNum(wxWbRoomVo.getRoomNum());
            wxWbRoom.setRoomName(wxWbRoomVo.getRoomName());
            wxWbRoom.setFloorNum(wxWbRoomVo.getFloorNum());
            wxWbRoom.setRoomType(wxWbRoomVo.getRoomType());
            wxWbRoom.setBulidId(wxWbRoomVo.getBulidId());
            wxWbRoom.setTwoDimension(getQrCode(request,wxWbRoom.getId(),sysUser.getId()));
            wxWbRoom.setRemarks(wxWbRoomVo.getRemarks());
            wxWbRoom.setSort(Integer.parseInt(wxWbRoomVo.getSort()));
            wxWbRoomDao.insert(wxWbRoom);
            return new ReturnResult(BaseConstant.DATABASE_SUCCEED_INSERT);
        } else {
            WxWbRoom wxWbRoom = wxWbRoomDao.selectByPrimaryKey(wxWbRoomVo.getId());
            wxWbRoom.setApplyId(wxWbRoomVo.getApplyId());
            wxWbRoom.setRoomNum(wxWbRoomVo.getRoomNum());
            wxWbRoom.setRoomName(wxWbRoomVo.getRoomName());
            wxWbRoom.setFloorNum(wxWbRoomVo.getFloorNum());
            wxWbRoom.setRoomType(wxWbRoomVo.getRoomType());
            wxWbRoom.setBulidId(wxWbRoomVo.getBulidId());
            wxWbRoom.setTwoDimension(getQrCode(request,wxWbRoom.getId(),sysUser.getId()));
            wxWbRoom.setRemarks(wxWbRoomVo.getRemarks());
            wxWbRoom.setSort(Integer.parseInt(wxWbRoomVo.getSort()));
            wxWbRoom.setUpdateTime(new Date());
            wxWbRoom.setUpdateUser(sysUser.getId());
            wxWbRoomDao.updateByPrimaryKey(wxWbRoom);
            return new ReturnResult(BaseConstant.DATABASE_SUCCEED_UPDATE);
        }
    }

    /**
     * 根据条件逻辑删除
     *
     * @param wxWbRoomVo 参数接受对象
     * @param sysUser 当前用户
     * @return ReturnResult
     * @author ding xu
     * @date 2019-11-27 17:42:26
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult remove(WxWbRoomVo wxWbRoomVo, SysUser sysUser) {
        //要修改的字段
        WxWbRoom wxWbRoom = new WxWbRoom();
        wxWbRoom.setRemoveTag(DictCode.BASE_REMOVE_TAG_DELETE);
        wxWbRoom.setUpdateUser(sysUser.getId());
        wxWbRoom.setUpdateTime(new Date());
        //筛选条件
        Example example = new Example(WxWbRoom.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(wxWbRoomVo.getId())) {
            criteria.andIn("id", Arrays.asList(wxWbRoomVo.getId().split(",")));
        }
        criteria.andEqualTo("removeTag", DictCode.BASE_REMOVE_TAG_NORMAL);
        wxWbRoomDao.updateByExampleSelective(wxWbRoom, example);
        return new ReturnResult(ErrorCode.CODE_0, BaseConstant.DATABASE_SUCCEED_DEL);
    }

    /**
     * 根据条件物理删除
     *
     * @param wxWbRoomVo 参数接受对象
     * @param sysUser      当前用户
     * @return ReturnResult
     * @author ding xu
     * @date 2019-11-27 17:42:26
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult delete(WxWbRoomVo wxWbRoomVo, SysUser sysUser) {
        //筛选条件
        Example example = new Example(WxWbRoom.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(wxWbRoomVo.getId())) {
            criteria.andIn("id", Arrays.asList(wxWbRoomVo.getId().split(",")));
        }
        wxWbRoomDao.deleteByExample(example);
        return new ReturnResult(ErrorCode.CODE_0, BaseConstant.DATABASE_SUCCEED_DEL);
    }

    @Override
    public ReturnResult importExcel(HttpServletRequest request,MultipartFile file, SysUser sysUser, String applyId) {
        ExcelImportResult<WxWbRoomExportVo> result = EasyPoiUtil.importExcelResult(file, 1, 1, WxWbRoomExportVo.class);
        List<WxWbRoomExportVo> WxWbRoomExportVoList =  result.getList();
        //获取场地列表map
        Map<String,String> wbWbBulidMaps= ListToMapUtil.listMaptoMap(wxWbBulidDao.selectToHashMap(new WxWbBulidVo(applyId)));
        List<WxWbRoom> wxWxWbRoomList=new ArrayList<WxWbRoom>();
        for(WxWbRoomExportVo wxWbRoomExportVo:WxWbRoomExportVoList){
            WxWbRoom wxWbRoomVo=new WxWbRoom(sysUser);
            wxWbRoomVo.setApplyId(applyId);
            wxWbRoomVo.setRoomNum(wxWbRoomExportVo.getRoomNum());
            wxWbRoomVo.setRoomName(wxWbRoomExportVo.getRoomName());
            wxWbRoomVo.setFloorNum(wxWbRoomExportVo.getFloorNum());
            wxWbRoomVo.setRoomType(wxWbRoomExportVo.getRoomType());
            wxWbRoomVo.setBulidId(wbWbBulidMaps.get(wxWbRoomExportVo.getBulidId()));
            wxWbRoomVo.setRemarks(wxWbRoomExportVo.getRemarks());
            wxWbRoomVo.setTwoDimension(getQrCode(request,wxWbRoomVo.getId(),sysUser.getId()));
            wxWbRoomVo.setSort(Integer.parseInt(wxWbRoomExportVo.getSort()));
            wxWbRoomVo.setApplyId(applyId);
            wxWxWbRoomList.add(wxWbRoomVo);
        }
        wxWbRoomDao.insertList(wxWxWbRoomList);
        if (result.isVerfiyFail()) {
            // 如果错误，打印出提醒，直接返回
            int successNum = 0;
            int failNum = result.getFailList().size();
            if (result.getList() != null && result.getList().size() > 0) {
                successNum = result.getList().size();
            }
            String errorMsg = String.format("共导入%s条，成功%s条，失败%s条。", successNum + failNum, successNum, failNum);
            List<WxWbRoomExportVo> failList = result.getFailList();
            // 需要将成功条数也返回
            Map<String, Object> resutlMap = new HashMap<>();
            resutlMap.put("failList", failList);
            return new ReturnResult(ErrorCode.CODE_1, resutlMap, errorMsg);
            //return new ReturnResult(wxEducationUserShow);
        }
        int successNumber =0;
        if (result.getList() != null && result.getList().size() > 0) {
            successNumber = result.getList().size();
        }
        String sucess = String.format("共导入%s条，成功%s条，失败0条。", successNumber, successNumber);
        return new ReturnResult(ErrorCode.CODE_0,"" , sucess);
    }

    private String getQrCode(HttpServletRequest request, String id, String memId) {
        String qrCode = "";
        // String getContextPath = request.getContextPath();
        // String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + getContextPath + "/";
        String realPath = FilePathUtil.acceptCheckRealPath(request);
        String path = realPath + "/upload/wbroom/" + id + ".png";
        File dicFile = new File(realPath + "/upload/wbroom/");
        if  (!dicFile .exists()  && !dicFile .isDirectory()) {
            dicFile .mkdir();
        }
        try {
            File file = new File(path);
            if (file.exists()) {
                // 删除问卷，重新生成
                file.delete();
            }
            OutputStream out = new FileOutputStream(path);
            new SimpleQrcodeGenerator().generate(id+"&"+"1").toStream(out);//设备type为2
            //添加到附件列表
            String fileName = id;
            //文件类型
            String type = BaseUtil.acceptFileType(fileName);
            SysFile sysFile = new SysFile();
            sysFile.setId(BaseUtil.uId());
            sysFile.setFileName(fileName);
            sysFile.setExtendName(type);
            sysFile.setObjectId(StringUtils.isNotEmpty(id) ? id : BaseUtil.uId());
            sysFile.setStorageType(DictCode.STORAGE_TYPE_LOCALHOST);
            sysFile.setPath("/upload/wbroom/" + id + ".png");
            sysFile.setType("wbroom");
            sysFile.setCreatorId(memId);
            sysFile.setRemoveTag(DictCode.BASE_REMOVE_TAG_NORMAL);
            sysFile.setCreateTime(new Date());
            //插入到数据库
            //删除原文件
            SysFile sysFileSearch=new SysFile();
            sysFileSearch.setObjectId(sysFile.getObjectId());
            List<SysFile> sysFiles=sysFileDao.select(sysFileSearch);
            if(sysFiles.size()>0){
                for(SysFile s:sysFiles){
                    sysFileDao.delete(s);
                }
            }
            sysFileDao.insert(sysFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return id;
    }


}